/**
 * @file     removeNthFromEnd.js
 * @brief    [19. 删除链表的倒数第 N 个结点](https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/)
 * @author   Zhu
 * @date     2023-06-18 21:23
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * 当头结点导致判断不好做时，使用哑结点
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
    const dummy = new ListNode();
    dummy.next = head;
    let pre = dummy;
    let post = dummy;

    let index = 1; // 正数的第i个节点
    while (pre) {
        pre = pre.next;
        if (pre == null) {
            post.next = post.next?.next ?? null;
            break;
        }
        if (index > n) {
            post = post.next;
        }
        index++;
    }

    return dummy.next;
};
